<?php

/* @var $factory \Illuminate\Database\Eloquent\Factory */

use App\Model;
use App\Models\AssetAffiliation;
use App\Models\AssetBrand;
use App\Models\AssetCategory;
use App\Models\AssetKeeper;
use App\Models\AssetLocation;
use App\Models\AssetStock;
use App\Models\AssetStockChangeHistory;
use App\Models\AssetStockChangeHistoryAction;
use App\Models\AssetVendor;
use App\Models\User;
use Faker\Generator as Faker;

$factory->define(AssetStock::class, function (Faker $faker) {
    $primaryAssetCategories = AssetCategory::whereNull('parent_id')->get();
    $primaryCategory = $faker->randomElement($primaryAssetCategories);
    $subCategory = $faker->randomElement($primaryCategory->children);
    $price1 = $faker->randomNumber(2);
    $price2 = $faker->randomNumber(2);
    $initQuantity = $faker->randomNumber(3);
    return [
        'name' => $faker->name,
        'description' => $faker->paragraph,
        'product_model_number' => $faker->creditCardNumber,
        'init_quantity' => $initQuantity,
        'available_quantity' => $initQuantity,
        'total_quantity' => $initQuantity,
        'checkout_quantity' => 0,
        'marking_price_per_unit' => max($price1, $price2),
        'bid_price_per_unit' => min($price1, $price2),
        'category_id' => $primaryCategory->id,
        'sub_category_id' => $subCategory->id,
        'affiliation_id' => function () {
            return factory(AssetAffiliation::class)->create()->id;
        },
        'brand_id' => function () {
            return factory(AssetBrand::class)->create()->id;
        },
        'keeper_id' => function () {
            return factory(AssetKeeper::class)->create()->id;
        },
        'vendor_id' => function () {
            return factory(AssetVendor::class)->create()->id;
        },
        'location_id' => function () {
            return factory(AssetLocation::class)->create()->id;
        },
    ];
});

$factory->define(AssetStockChangeHistory::class, function (Faker $faker){
    $assetStock = AssetStock::first();
    $user = User::first();
    if (empty($assetStock)) {
        $assetStock = factory(AssetStock::class)->create();
    }
    $actions = AssetStockChangeHistoryAction::all();
    $action = $faker->randomElement($actions->toArray());
    $quantity = $faker->numberBetween(1, 10);
    if ($action['name'] !== "添加") {
        $quantity = $quantity * -1;
    }
    return [
        "comment" => $faker->word,
        "quantity" => $quantity,
        "action_id" => $action['id'],
        "user_id" => $user->id,
        "asset_stock_id" => $assetStock->id
    ];

});
